package com.atguigu.gmall.product.service;

import com.atguigu.gmall.common.cache.GmallCache;
import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.product.*;
import com.atguigu.gmall.product.mapper.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.injector.methods.Insert;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.databind.annotation.JsonAppend;
import com.sun.org.apache.regexp.internal.RE;
import net.bytebuddy.asm.Advice;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.ParameterResolutionDelegate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * description:
 * create by sxy 2021/5/8
 */
@Service
public class ManagerServiceImpl implements ManagerService {


    //查询一级分类集合
    @Autowired
    private BaseCategory1Mapper baseCategory1Mapper;
    @Autowired
    private BaseCategory2Mapper baseCategory2Mapper;

    @Autowired
    private BaseCategory3Mapper baseCategory3Mapper;
    @Autowired
    private BaseAttrInfoMapper baseAttrInfoMapper;
    @Autowired
    private BaseAttrValueMapper baseAttrValueMapper;
    @Autowired
    private BaseTrademarkMapper baseTrademarkMapper;


    @Override
    public List<BaseCategory1> getCategory1() {
        return baseCategory1Mapper.selectList(null);
    }

    //查询二级分类集合
    @Override
    public List<BaseCategory2> getCategory2(long category1Id) {
        return baseCategory2Mapper.selectList(new QueryWrapper<BaseCategory2>()
                .eq("category1_id", category1Id));
    }

    @Override
    public List<BaseCategory3> getCategory3(long category2Id) {
        return baseCategory3Mapper.selectList(new QueryWrapper<BaseCategory3>()
                .eq("category2_id", category2Id));
    }

    @Override
    public List<BaseAttrInfo> attrInfoList(long category1Id, long category2Id, long category3Id) {
        return baseAttrInfoMapper.attrInfoList(category1Id, category2Id, category3Id);
    }

    //添加平台属性
    @Override
    public void saveAttrInfo(BaseAttrInfo baseAttrInfo) {

        // 什么情况下 是添加，什么情况下是更新，修改 根据baseAttrInfo 的Id
        // baseAttrInfo
        if (baseAttrInfo.getId() != null) {
            //修改数据

            baseAttrInfoMapper.updateById(baseAttrInfo);
        } else {
            //新增
            baseAttrInfoMapper.insert(baseAttrInfo);
        }


        //平台属性值遍
        List<BaseAttrValue> attrValueList = baseAttrInfo.getAttrValueList();
        attrValueList.stream().forEach(baseAttrValue -> {
            //外键
            baseAttrValue.setAttrId(baseAttrInfo.getId());

            baseAttrValueMapper.insert(baseAttrValue);
        });
    }

    //根据attrId 查询平台属性对象
    @Override
    public BaseAttrInfo getAttrInfo(Long attrId) {
        BaseAttrInfo baseAttrInfo = baseAttrInfoMapper.selectById(attrId);
        // 查询到最新的平台属性值集合数据放入平台属性中！
        baseAttrInfo.setAttrValueList(getAttrValueList(attrId));
        return baseAttrInfo;

    }


    //根据属性id获取属性值
    private List<BaseAttrValue> getAttrValueList(Long attrId) {
        // select * from baseAttrValue where attrId = ?
        QueryWrapper<BaseAttrValue> qw = new QueryWrapper<>();
        qw.eq("attr_id", attrId);
        List<BaseAttrValue> attrValueList = baseAttrValueMapper.selectList(qw);
        return attrValueList;
    }

    @Override
    public IPage baseTrademark(Integer page, Integer limit) {

        Page<BaseTrademark> page1 = new Page<>(page, limit);
        return baseTrademarkMapper.selectPage(page1, null);
    }

    @Override
    public IPage spuInfoList(Integer page, Integer limit, Long category3Id) {

        return spuInfoMapper.selectPage(new Page<>(page, limit), new QueryWrapper<SpuInfo>()
                .eq("category3_id", category3Id));
    }

    @Override
    public List<BaseTrademark> getTrademarkList() {

        return baseTrademarkMapper.selectList(null);
    }

    @Override
    public List<BaseSaleAttr> baseSaleAttrList() {
        return baseSaleAttrMapper.selectList(null);
    }

    //商品的添加
    @Override
    public void saveSpuInfo(SpuInfo spuInfo) {
        //1 商品表
        spuInfoMapper.insert(spuInfo);
        //2 图片表
        List<SpuImage> spuImageList = spuInfo.getSpuImageList();
        if (!CollectionUtils.isEmpty(spuImageList)) {
            spuImageList.forEach(spuImage -> {
                //设置外键
                spuImage.setSpuId(spuInfo.getId());
                int insert = spuImageMapper.insert(spuImage);
                System.out.println(insert);
            });
        }
        //3 销售属性表
        spuInfo.getSpuSaleAttrList().forEach(spuSaleAttr -> {
            //设置外键
            spuSaleAttr.setSpuId(spuInfo.getId());
            spuSaleAttrMapper.insert(spuSaleAttr);
            //4 销售属性值表
            spuSaleAttr.getSpuSaleAttrValueList().forEach(spuSaleAttrValue -> {
                //设置外键
                spuSaleAttrValue.setSpuId(spuInfo.getId());
                //销售属性名
                spuSaleAttrValue.setSaleAttrName(spuSaleAttr.getSaleAttrName());

                spuSaleAttrValueMapper.insert(spuSaleAttrValue);
            });
        });

    }

    //根据商品id  spuid 查询所有图片 显示在sku添加页面，为了叫管理员来选择
    @Override
    public List<SpuImage> spuImageList(Long spuId) {
        return spuImageMapper.selectList(new QueryWrapper<SpuImage>().
                eq("spu_id", spuId));

    }

    //根据商品id spuid查找销售属性 及值表
    @Override
    public List<SpuSaleAttr> spuSaleAttrList(Long spuId) {
        return spuSaleAttrMapper.spuSaleAttrList(spuId);
    }

    //添加skuinfo
    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {

        //1库存表
        skuInfoMapper.insert(skuInfo);
        //2 库存的图片表
        skuInfo.getSkuImageList().forEach(skuImage -> {
            skuImage.setSkuId(skuInfo.getId());

            skuImageMapper.insert(skuImage);
        });
        //3 库存与平台属性及值的中间表
        skuInfo.getSkuAttrValueList().forEach(skuAttrValue -> {
            skuAttrValue.setSkuId(skuInfo.getId());
            skuAttrValueMapper.insert(skuAttrValue);
        });
        //4 库存与销售属性及值的中间表
        skuInfo.getSkuSaleAttrValueList().forEach(skuSaleAttrValue -> {
            //设置库存id
            skuSaleAttrValue.setSkuId(skuInfo.getId());
            //设置商品id
            skuSaleAttrValue.setSpuId(skuInfo.getSpuId());

            skuSaleAttrValueMapper.insert(skuSaleAttrValue);
        });
    }

    //分页查询sku列表
    @Override
    public IPage skuListPage(Integer page, Integer limit) {

        return skuInfoMapper.selectPage(new Page(page, limit), null);
    }

    //上架
    @Override
    public void onSale(Long skuId) {
        //修改db库中库存表 is_sale
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.ISSALE);
        skuInfoMapper.updateById(skuInfo);
        //TODO 发消息更新es索引
    }

    //下架
    @Override
    public void cancelSale(Long skuId) {
        SkuInfo skuInfo = new SkuInfo();
        skuInfo.setId(skuId);
        skuInfo.setIsSale(SkuInfo.CANCELSALE);
        skuInfoMapper.updateById(skuInfo);
        //TODO 发消息 删除索引库

    }

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient redissonClient;

    @Override
//    @GmallCache(prefix = "sku:")这个已经实现缓存了，就不需要注解缓存了
    //使用redisson 来解决分布式锁的问题
    public SkuInfo getSkuInfo(Long skuId) {
        //缓存KEY
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        //1 查询缓存
        SkuInfo skuInfo = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        if (null == skuInfo) {
            //查询之前先上锁 解决缓存击穿问题
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            RLock lock = redissonClient.getLock(cacheLockKey);
            try {
                //过期不候的锁 JUC
                //参数1：获取锁的时间 过了这个时间就不再获取了
                //参数2：获取到锁之后 锁的过期时间
                //参数3：单位
                boolean tryLock = lock.tryLock(1, 2, TimeUnit.SECONDS);
                if (tryLock) {
                    //获取到了锁
                    //2没有  查询db  返回一份
                    skuInfo = skuInfoMapper.selectById(skuId);
                    if (null != skuInfo) {
                        skuInfo.setSkuImageList(skuImageMapper.
                                selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId)));
                        //在保存一份，返回
                        redisTemplate.opsForValue().set(cacheKey, skuInfo,
                                RedisConst.SKUKEY_TIMEOUT + new Random().nextInt(300),//缓存雪崩
                                TimeUnit.SECONDS);

                    } else {
                        //缓存穿透 有结果 是空的
                        skuInfo = new SkuInfo();
                        //在保存一份，返回
                        redisTemplate.opsForValue().set(cacheKey,
                                skuInfo, 5,
                                TimeUnit.MINUTES);
                    }
                    //解锁
                    lock.unlock();
                } else {
                    //没有获取到锁
                    try {
                        Thread.sleep(2000);
                        return (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }

        //有 直接返回
        return skuInfo;
    }

    //根据skuid 获取skuinfo信息
    /*//直接使用redis 来解决分布式锁的问题
    @Override
    public SkuInfo getSkuInfo(Long skuId) {
        //缓存KEY
        String cacheKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKUKEY_SUFFIX;
        //1先查询缓存
        SkuInfo skuInfo  = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
        //2有  直接返回
        if (null == skuInfo) {
            //3 没有  上分布式锁之后解决缓存击穿
            String cacheLockKey = RedisConst.SKUKEY_PREFIX + skuId + RedisConst.SKULOCK_SUFFIX;
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            Boolean lock = redisTemplate.opsForValue().setIfAbsent(cacheKey, uuid,2,TimeUnit.SECONDS);
            if(lock){
                //获取到了锁
                // 然后查询db
                skuInfo = skuInfoMapper.selectById(skuId);
                if (null != skuInfo) {
                    skuInfo.setSkuImageList(skuImageMapper.
                            selectList(new QueryWrapper<SkuImage>().eq("sku_id", skuId)));
                    //在保存一份，返回
                    redisTemplate.opsForValue().set(cacheKey, skuInfo,
                            RedisConst.SKUKEY_TIMEOUT+new Random().nextInt(300),//缓存雪崩
                            TimeUnit.SECONDS);

                } else {
                    //缓存穿透 有结果 是空的
                    skuInfo = new SkuInfo();
                    //在保存一份，返回
                    redisTemplate.opsForValue().set(cacheKey,
                            skuInfo, 5,
                            TimeUnit.MINUTES);
                    //删除锁前先判断是不是自己的锁
                 *//*   Object k = redisTemplate.opsForValue().get(cacheLockKey);
                    if (uuid.equals(k)) {
                        //是自己的锁
                        redisTemplate.delete(cacheLockKey);
                    }*//*
                 //lua脚本保证原子性
                    String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return tostring(redis.call('del',KEYS[1])) else return 0 end";
                    this.redisTemplate.execute(new DefaultRedisScript<>(script), Collections.singletonList(cacheLockKey), uuid);


                }
            }else {
                //没有获取到锁
                try {
                    Thread.sleep(2000);
                    return  skuInfo  = (SkuInfo) redisTemplate.opsForValue().get(cacheKey);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
        }
     return skuInfo;
    }*/


    //三级分类的视图
    @Override
    @GmallCache(prefix = "baseCategoryView：")
    public BaseCategoryView getBaseCategoryView(Long category3Id) {

        return baseCategoryViewMapper.selectById(category3Id);
    }

    //	3. 销售属性及值及红边框
    @Override
    @GmallCache(prefix = "spuSaleAttrValueChecked：")
    public List<SpuSaleAttr> getSpuSaleAttrValueChecked(Long skuId, Long spuId) {
        return spuSaleAttrMapper.getSpuSaleAttrValueChecked(skuId, spuId);
    }

    //  4.销售属性组合获取对应的skuid
    @Override
    @GmallCache(prefix = "valuesSkuJson：")
    public Map getValuesSkuJson(Long spuId) {
        Map result = new HashMap();
        List<Map> mapList = skuSaleAttrValueMapper.getValuesSkuJson(spuId);
        mapList.forEach(map -> {
            result.put(map.get("valueIds"), map.get("sku_id"));
        });
        return result;
    }

    @Override
    public BigDecimal getPrice(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectById(skuId);
        BigDecimal price = skuInfo.getPrice();
        if (null != price) {
            return price;
        } else {
            return null;
        }


    }

    @Autowired
    BaseCategoryViewMapper baseCategoryViewMapper;
    @Autowired
    private SpuInfoMapper spuInfoMapper;
    @Autowired
    private BaseSaleAttrMapper baseSaleAttrMapper;
    @Autowired
    private SpuImageMapper spuImageMapper;
    @Autowired
    private SpuSaleAttrMapper spuSaleAttrMapper;
    @Autowired
    private SpuSaleAttrValueMapper spuSaleAttrValueMapper;
    @Autowired
    private SkuInfoMapper skuInfoMapper;
    @Autowired
    private SkuImageMapper skuImageMapper;
    @Autowired
    private SkuAttrValueMapper skuAttrValueMapper;
    @Autowired
    private SkuSaleAttrValueMapper skuSaleAttrValueMapper;


}
